package com.ikkong.shine.controller;

import java.util.List;

import com.ikkong.common.config.MainConfig;
import com.ikkong.shine.model.DataConnection;
import com.ikkong.shine.model.DbSql;
import com.ikkong.shine.service.DataConnectionService;
import com.ikkong.shine.service.DbSqlService;
import com.ikkong.shine.service.impl.DataConnectionServiceImpl;
import com.ikkong.shine.service.impl.DbSqlServiceImpl;
import com.ikkong.system.controller.base.UrlPermissController;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.druid.DruidPlugin;

public class GetDataController extends UrlPermissController  {
	
	DbSqlService dbsqlservice = new DbSqlServiceImpl();
	
	DataConnectionService dataconnectionservice=new DataConnectionServiceImpl(); 
	
	public void getSqlConn(){
		DataConnection dc=new DataConnection();
		String username=dc.getUsername().toString().trim();
		String password=dc.getPassword().toString().trim();
		String url=dc.getUrl().toString().trim();
		String driver=dc.getDriver().toString().trim();
		String id=dc.getId().toString().trim();
		
		DbSql ds=new DbSql();
		String type=ds.getType().toString();
		DruidPlugin druidPlugin=null;
		ActiveRecordPlugin arp =null;
		if(!MainConfig.dbconfigs.contains(id)){//判断数据源是否已经启动
			druidPlugin = new DruidPlugin(url,username,password,driver);//初始化数据库连接池
			arp = new ActiveRecordPlugin(id,druidPlugin);//初始化数据源
			druidPlugin.start();//启动连接池
			arp.start();//启动数据源
			MainConfig.dbconfigs.add(id);//将数据源名称保存在内存常量中
		}
		String sql="";
		if("1".equals(type)){
			sql=""+ds.getSqlstring()+"";
		}
        List<com.jfinal.plugin.activerecord.Record> recordList=null;
        try {
        	recordList=Db.use(dc.getId().toString()).find(sql);//.paginateByFullSql(1, 1, totalRowSql, sql);
        }catch (Exception e) {
			//sql执行异常，关闭数据库连接池和数据源
			if(druidPlugin !=null){
				druidPlugin.stop();
			}
			if(null != arp){
				arp.stop();
			}
			MainConfig.dbconfigs.remove(dc.getId().toString());//移除添加的数据源名称
			renderJson(error("sql执行异常"));
			return;
		}
		if(null==recordList){
			renderJson(error("查询失败"));
			return;
		}else{
			renderJson(success("查询成功"));
		}
	}
}
